package com.asktgapp.user.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChooseTypeFragment;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.NewEngineerDetailVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChooseBrandActivity;
import com.asktgapp.user.activity.ChooseCityActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.bigkoo.pickerview.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 更新工程师个人信息页面
 */

public class UpdateEngineerInfoFragment extends BaseFragment {
    //咨询价格
    @InjectView(R.id.etPrice)
    EditText etPrice;
    //所在地址
    @InjectView(R.id.tvAddress)
    TextView tvAddress;
    //电话
    @InjectView(R.id.etPhone)
    EditText etPhone;
    //所在公司
    @InjectView(R.id.et_auth_company)
    EditText mCompanyEt;
    //公司职位
    @InjectView(R.id.et_auth_job)
    EditText mJobEt;
    //擅长领域
    @InjectView(R.id.et_auth_strong_point)
    TextView mStrongPoint;
    //培训经历
    @InjectView(R.id.etPeiXun)
    EditText etPeiXun;
    //自我介绍
    @InjectView(R.id.etZiWo)
    EditText etZiWo;


    @InjectView(R.id.et_auth_introduction1)
    EditText et_auth_introduction1;//推荐理由1
    @InjectView(R.id.et_auth_introduction2)
    EditText et_auth_introduction2;//推荐理由2
    @InjectView(R.id.et_auth_introduction3)
    EditText et_auth_introduction3;//推荐理由3
    //下一步
    @InjectView(R.id.tv_auth_next)
    TextView mNextStep;

    @InjectView(R.id.startTime)
    TextView startTime;
    @InjectView(R.id.endTime)
    TextView endTime;
    @InjectView(R.id.tvGoodAtBrand)
    TextView tvGoodAtBrand;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_update_engineer_info, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mNextStep.setOnClickListener(this);
        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        tvAddress.setOnClickListener(this);
        mStrongPoint.setOnClickListener(this);
        tvGoodAtBrand.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.endTime:
                showTimeS(false);
                break;
            case R.id.startTime:
                showTimeS(true);
                break;
            case R.id.tv_auth_next:
                update();
                break;
            case R.id.tvAddress:

                Intent address = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(address, 300);
                break;
            case R.id.et_auth_strong_point:
                ChooseTypeFragment chooseTypeFragment = new ChooseTypeFragment(new ChooseTypeFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mStrongPoint.setText(s[1]);
                        mSelectedTypeId = s[0];
                    }
                }, mTypeList, "请选择设备类型");
                chooseTypeFragment.show(getFragmentManager(), "ChooseTypeFragment");

                break;
            case R.id.tvGoodAtBrand:
                if (Util.isEmpty(mStrongPoint.getText().toString().trim())) {
                    showTost("请先选择设备擅长的类型", 1);
                    return;
                }
                Intent intent = new Intent(getActivity(), ChooseBrandActivity.class);
                intent.putExtra("typeId", mSelectedTypeId);
                startActivityForResult(intent, 200);
                break;
        }

    }

    private void showTimeS(final boolean isStart) {
        getBaseActivity().hideSoftKeybord();
        TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                if (isStart) {
                    Log.e("time", date2.toString());
                    startTime.setText(Util.getShorDateH(date2));
                } else {
                    endTime.setText(Util.getShorDateH(date2));
                }
//                if (!Utils.isGoneDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
//                    showTost("不能选择将来的时间！", 1);
//                }
//                else
//                    mMadeDate.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

            }
        })
                .setType(TimePickerView.Type.HOURS_MINS)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    private String mSelectedBrandId, mSelectedTypeId;
    private String mAreaId, mCityId;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200) {
                tvGoodAtBrand.setText(data.getStringExtra("brand"));
                mSelectedBrandId = data.getStringExtra("brandId");
            }
            if (requestCode == 300) {
                mAreaId = data.getStringExtra("areaId");
                mCityId = data.getStringExtra("cityId");
                tvAddress.setText(data.getStringExtra("area") + "  " + data.getStringExtra("city"));
            }
        }
    }

    @Override
    public void loadData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList = response.body().getResult();
                    if (!TextUtils.isEmpty(strongPoint)) {
                        for (int i = 0; i < mTypeList.size(); i++) {
                            if (strongPoint.equals(mTypeList.get(i).getName()))
                                mSelectedTypeId = mTypeList.get(i).getId();
                        }
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });

        getInfo();

    }

    private void getInfo() {
        HashMap params1 = new HashMap();
        params1.put("id", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params1.put("page", 1);
        params1.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<NewEngineerDetailVO>> call = ApiUtil.getInstance().create(Apiservice.class).projecterDetail(params1);
        call.enqueue(new Callback<ApiResponseBody<NewEngineerDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<NewEngineerDetailVO>> call, Response<ApiResponseBody<NewEngineerDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    NewEngineerDetailVO bean = response.body().getResult();
                    if (bean != null) {
                        String pro = bean.getProviceName().replaceAll("省", "");
                        String city = bean.getCityName().replaceAll("市", "");
                        if (TextUtils.isEmpty((pro + " " + city).trim()))
                            tvAddress.setText("未知地区");
                        else
                            tvAddress.setText(pro + " " + city);

                        etPhone.setText(bean.getPhone());
                        etPrice.setText(bean.getAdvisoryPrice());
                        tvGoodAtBrand.setText(bean.getBrandName());
                        mSelectedBrandId = bean.getBrandId();
                        strongPoint = bean.getGoodFeild();
                        if (mTypeList != null && mTypeList.size() > 0) {
                            for (int i = 0; i < mTypeList.size(); i++) {
                                if (strongPoint.equals(mTypeList.get(i).getName()))
                                    mSelectedTypeId = mTypeList.get(i).getId();
                            }
                        }
                        mStrongPoint.setText(strongPoint);
                        mCompanyEt.setText(bean.getCompany());
                        mJobEt.setText(bean.getPosition());
                        if (!TextUtils.isEmpty(bean.getOnlineTime())) {
                            String[] time = bean.getOnlineTime().split("-");
                            if (time.length == 2) {
                                startTime.setText(time[0]);
                                endTime.setText(time[1]);
                            }
                        }
                        mCityId = bean.getCityId();
                        mAreaId = bean.getProvinceId();

                        if (!TextUtils.isEmpty(bean.getRecommendReason())) {
                            String[] recomm = bean.getRecommendReason().trim().split("##");
                           if(recomm.length==1){
                               et_auth_introduction1.setText(recomm[0].trim());
                           }else if(recomm.length==2){
                               et_auth_introduction1.setText(recomm[0].trim());
                               et_auth_introduction2.setText(recomm[1].trim());
                           }else if(recomm.length==3){
                               et_auth_introduction1.setText(recomm[0].trim());
                               et_auth_introduction2.setText(recomm[1].trim());
                               et_auth_introduction3.setText(recomm[2].trim());
                           }
                        }
                        etPeiXun.setText(bean.getWorkExperience());
                        etZiWo.setText(bean.getDescription());
//                        mSelfIntroduciton.setText(bean.getRecommendReason());
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<NewEngineerDetailVO>> call, Throwable t) {
                inVisibleLoading();
                visibleNoData();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
        addSubscription(call);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    private String strongPoint;

    private void update() {
        String price = etPrice.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String start = startTime.getText().toString().trim();
        String end = endTime.getText().toString().trim();
        strongPoint = mStrongPoint.getText().toString().trim();
        String recommendT = et_auth_introduction1.getText().toString();
        String position = mJobEt.getText().toString().trim();
        String brand = tvGoodAtBrand.getText().toString().trim();
        if (Util.isEmpty(price)) {
            showTost("请输入咨询费用", 0);
            return;
        }
//        if (Double.valueOf(price.trim()) < 1) {
//            showTost("咨询费用不能低于1元", 0);
//            return;
//        }
        if (Util.isEmpty(mAreaId) || Util.isEmpty(mCityId)) {
            showTost("请选择您所在地区", 0);
            return;
        }
        if (Util.isEmpty(start)) {
            showTost("请选择在线时间", 0);
            return;
        }
        if (Util.isEmpty(end)) {
            showTost("请选择在线时间", 0);
            return;
        }
        if (Util.isEmpty(strongPoint)) {
            showTost("请选择擅长设备类型", 0);
            return;
        }
        if (Util.isEmpty(brand)) {
            showTost("请选择擅长品牌", 0);
            return;
        }
        if (Util.isEmpty(recommendT)) {
            showTost("请至少填写一项推荐理由", 0);
            return;
        }

        String recommend = "";

        if (!TextUtils.isEmpty(et_auth_introduction1.getText().toString()))
            recommend += et_auth_introduction1.getText().toString() ;
        if (!TextUtils.isEmpty(et_auth_introduction2.getText().toString()))
            recommend += "##" + et_auth_introduction2.getText().toString();
        if (!TextUtils.isEmpty(et_auth_introduction3.getText().toString()))
            recommend += "##" + et_auth_introduction3.getText().toString();




        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("price", price);
        params.put("province", mAreaId);
        params.put("city", mCityId);
        params.put("phone", phone);
        params.put("onlineTime", start + "-" + end);
        params.put("position", position);
        params.put("goodFeild", strongPoint);
        params.put("recommendReason", recommend);
        params.put("brand", mSelectedBrandId);
        params.put("trainExperience", etPeiXun.getText().toString().trim());
        params.put("description", etZiWo.getText().toString().trim());
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.updateProjectorDetail(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    showTost("修改成功", 0);
                    getActivity().onBackPressed();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }
}
